package cn.itcast.controller;

import cn.itcast.entity.Result;
import cn.itcast.service.ReportService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import cn.itcast.constant.MessageConstant;
import cn.itcast.service.MemberService;
import cn.itcast.service.SetmealService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private ReportService reportService;

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    /**
     * 每月收入统计柱状图统计
     */
    @GetMapping("/income")
    public Result incomeStatistics() {

        Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();

        Calendar calendar = Calendar.getInstance();//获取日历对象，模拟时间就是当前时间
        //计算过去一年的12个月
        calendar.add(Calendar.MONTH, -12);//获取当前时间，往前推12个月
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);//获取当前时间往后推一个月的时间
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy-MM").format(date));
        }
        map.put("months", months);
        List<Integer> income = reportService.income(months);
        map.put("income", income);
        return new Result(true, null, map);
    }

    /**
     * 每月预约支付统计
     * @return
     */
    @GetMapping("/statistics")
    public Result statisticsNumber(){
        Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();

        Calendar calendar = Calendar.getInstance();//获取日历对象，模拟时间就是当前时间
        //计算过去一年的12个月
        calendar.add(Calendar.MONTH, -12);//获取当前时间，往前推12个月
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);//获取当前时间往后推一个月的时间
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy-MM").format(date));
        }
        map.put("months", months);
//        List<Integer> income = reportService.income(months);
        List<Integer>  order = reportService.findByOrderNumber(months);
        map.put("ordernumber", order);
        List<Integer>  pay = reportService.findByPayNumber(months);
        map.put("paynumber", pay);

        return new Result(true, null, map);
    }

    /**
     * 运营数据统计
     * @return
     */
    @GetMapping("/business")
    public Result business(){
        try {
            Map<String,Object> map = reportService.getBusiness();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 导出运营数据
     * @return
     */
    @GetMapping("/export/business")
    public Result exportBusiness(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String, Object> map = reportService.getBusiness();
            //取出返回的结果，准备将报表数写入到excel表中
           String reportDate = (String) map.get("reportDate");
           Integer todayNewMember = (Integer) map.get("todayNewMember");
           Integer totalMember = (Integer) map.get("totalMember");
           Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");
           Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");
           Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
           Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
           Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
           Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
           Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
           Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");
           List<Map> list = (List<Map>) map.get("hotSetmeal");

            String filePath = ResourceUtils.getFile("classpath:static/template/report_template.xlsx").getPath();
            System.out.println(filePath);
            System.out.println(File.separator);
           //基于excel模板文件创建一个excel文件对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);
            //获取第三行
            XSSFRow xssfRow = sheet.getRow(2);
            XSSFCell cell = xssfRow.getCell(5);
            cell.setCellValue(reportDate);

            xssfRow = sheet.getRow(4);
            xssfRow.getCell(5).setCellValue(todayNewMember);

            xssfRow = sheet.getRow(4);
            xssfRow.getCell(7).setCellValue(totalMember);

            xssfRow = sheet.getRow(5);
            xssfRow.getCell(5).setCellValue(thisWeekNewMember);

            xssfRow = sheet.getRow(5);
            xssfRow.getCell(7).setCellValue(thisMonthNewMember);

            xssfRow = sheet.getRow(7);
            xssfRow.getCell(5).setCellValue(todayOrderNumber);

            xssfRow = sheet.getRow(7);
            xssfRow.getCell(7).setCellValue(todayVisitsNumber);

            xssfRow = sheet.getRow(8);
            xssfRow.getCell(5).setCellValue(thisWeekOrderNumber);

            xssfRow = sheet.getRow(8);
            xssfRow.getCell(7).setCellValue(thisWeekVisitsNumber);

            xssfRow = sheet.getRow(9);
            xssfRow.getCell(5).setCellValue(thisMonthOrderNumber);

            xssfRow = sheet.getRow(9);
            xssfRow.getCell(7).setCellValue(thisMonthVisitsNumber);

            int rowNum = 12 ;
            //热门套餐的数据
            for(Map map1 : list){
                String name = (String) map1.get("name");
                Long setmeal_count = (Long) map1.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map1.get("proportion");
                xssfRow=sheet.getRow(rowNum++);
                xssfRow.getCell(4).setCellValue(name);
                xssfRow.getCell(5).setCellValue(setmeal_count);
                xssfRow.getCell(6).setCellValue(proportion.doubleValue());
            }
            //使用输出流下载表格
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;filename=report.xlsx");
            excel.write(out);

            out.flush();
            out.close();
            excel.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);

        }
    }


    /*public static void main(String[] args) throws Exception {
        //获得日历对象,模拟时间就是当前时间
        Calendar calendar = Calendar.getInstance();
        //计算时间月份往前推送12个月
        calendar.add(Calendar.MONTH,-12);
        for (int i=0;i<12;i++){
            calendar.add(Calendar.MONTH,1);
            Date time = calendar.getTime();
            System.out.println(DateUtils.parseDate2String(time));
        }
    }*/
    @RequestMapping("/member/count")
    public Result memberReport() {
        HashMap<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();
        //获得日历对象,模拟时间就是当前时间
        Calendar calendar = Calendar.getInstance();
        //计算时间月份往前推送12个月
        calendar.add(Calendar.MONTH, -12);
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }
        map.put("months", months);

        List<Integer> memberCount = memberService.findMemberCountByMonth(months);
        map.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }

    @RequestMapping("/setmeals")
    public Result setmealReport() {
        /*HashMap<String, Object> data = new HashMap<>();
        List<String> setmealNames = new ArrayList<>();
        setmealNames.add("入职无忧体检套餐（男女通用）");
        setmealNames.add("粉红珍爱(女)升级TM12项筛查体检套餐");
        data.put("setmealNames",setmealNames);*/

        /*List<Map<String, Object>> setmealCount = new ArrayList<>();
        HashMap map1 = new HashMap();
        map1.put("name","入职无忧体检套餐（男女通用）");
        map1.put("value",200);
        HashMap map2 = new HashMap();
        map2.put("name","粉红珍爱(女)升级TM12项筛查体检套餐");
        map2.put("value",300);
        setmealCount.add(map1);
        setmealCount.add(map2);*/

        Map<String, Object> data = new HashMap<>();

        try {
            List<Map<String, Object>> setmealCount = setmealService.findSetmealOrderedCount();
            data.put("setmealCount", setmealCount);

            List<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> map : setmealCount) {
                String name = (String) map.get("name");
                setmealNames.add(name);
            }
            data.put("setmealNames", setmealNames);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }
}

